{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "40fce72e",
   "metadata": {},
   "source": [
    "Upgrade the day 1 project to summarize a webpage to use an Open Source model running locally via Ollama rather than OpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "89ab49a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from dotenv import load_dotenv\n",
    "from bs4 import BeautifulSoup\n",
    "import requests\n",
    "from IPython.display import Markdown, display\n",
    "from openai import OpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c67cad44",
   "metadata": {},
   "outputs": [],
   "source": [
    "headers = {\n",
    "    \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36\"\n",
    "}\n",
    "\n",
    "def fetch_website_contents(url):\n",
    "    \"\"\"\n",
    "    Return the title and contents of the website at the given url;\n",
    "    truncate to 2,000 characters as a sensible limit\n",
    "    \"\"\"\n",
    "    response = requests.get(url, headers=headers)\n",
    "    soup = BeautifulSoup(response.content, \"html.parser\")\n",
    "    title = soup.title.string if soup.title else \"No title found\"\n",
    "    if soup.body:\n",
    "        for irrelevant in soup.body([\"script\", \"style\", \"img\", \"input\"]):\n",
    "            irrelevant.decompose()\n",
    "        text = soup.body.get_text(separator=\"\\n\", strip=True)\n",
    "    else:\n",
    "        text = \"\"\n",
    "    return (title + \"\\n\\n\" + text)[:2_000]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "22d1ae67",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "API key found and looks good so far!\n"
     ]
    }
   ],
   "source": [
    "load_dotenv(override=True)\n",
    "api_key = os.getenv('OPENAI_API_KEY')\n",
    "\n",
    "# Check the key\n",
    "\n",
    "if not api_key:\n",
    "    print(\"No API key was found - please head over to the troubleshooting notebook in this folder to identify & fix!\")\n",
    "elif not api_key.startswith(\"sk-proj-\"):\n",
    "    print(\"An API key was found, but it doesn't start sk-proj-; please check you're using the right key - see troubleshooting notebook\")\n",
    "elif api_key.strip() != api_key:\n",
    "    print(\"An API key was found, but it looks like it might have space or tab characters at the start or end - please remove them - see troubleshooting notebook\")\n",
    "else:\n",
    "    print(\"API key found and looks good so far!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "251740b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "system_prompt=\"\"\"\n",
    "you are a quirky movie review assistant. Provide a short review of the movie based on the plot, characters, and overall experience.\n",
    "\"\"\"\n",
    "\n",
    "user_prompt=\"\"\"\n",
    "Here is the website content.Please provide a review of the movie based on the plot, characters, and overall experience.\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55b90cfc",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_movie_review(url):\n",
    "    \"\"\"\n",
    "    Get a movie review from the given url\n",
    "    \"\"\"\n",
    "    contents = fetch_website_contents(url)\n",
    "    messages = [\n",
    "       {\"role\": \"system\", \"content\": system_prompt},\n",
    "       {\"role\": \"user\", \"content\": user_prompt + contents} \n",
    "    ]\n",
    "\n",
    "    openai = OpenAI(base_url=\"http://localhost:11434/v1\", api_key=\"ollama\")\n",
    "    \n",
    "    response = openai.chat.completions.create(\n",
    "        model=\"llama3.2\",\n",
    "        messages=messages\n",
    "    )\n",
    "    return response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f72b4fe6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def review_movie(url):\n",
    "    review_movie= get_movie_review(url)\n",
    "    display(Markdown(review_movie))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "26cb59b9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "**A Fierce Tribute to Rani Lakshmibai: A Review of \"Manikarnika: The Queen of Jhansi\"**\n",
       "\n",
       "\"Manikarnika: The Queen of Jhansi\" is a powerful and epic biographical drama that tells the story of India's beloved queen, Lakshmibai, in a visually stunning manner. The film, directed by Krish Jagarlamudi and Kangana Ranaut, brings to life the tragic tale of Rani Lakshmibai, who led the Indian Rebellion of 1857 against the British East India Company.\n",
       "\n",
       "The movie boasts an impressive cast, including Kangana Ranaut, Jisshu Sengupta, Mohammed Zeeshan Ayyub, and Amitabh Bachchan, who delivers a remarkable narration. However, it's Kangana's performance that steals the show, bringing depth and nuance to her portrayal of the fearless and determined queen.\n",
       "\n",
       "The film's direction is both visually stunning and emotionally charged, with vivid depictions of 19th-century India. The cinematography by Kiran Deohans and Gnana Shekar V. S. is brilliant, capturing the grittiness and grandeur of historical events.\n",
       "\n",
       "One of the standout aspects of this movie is its portrayal of strong women in a patriarchal society. Lakshmibai's courage, intelligence, and conviction serve as an inspiration to audiences worldwide. The film also raises important questions about colonialism, imperialism, and the struggle for Indian independence.\n",
       "\n",
       "If there's one criticism to be made, it's that the pacing can feel a bit uneven at times. Additionally, some viewers may find certain scenes, such as those depicting violence against women, quite intense.\n",
       "\n",
       "Overall, \"Manikarnika: The Queen of Jhansi\" is an unforgettable cinematic experience that celebrates courage, friendship, and the unbreakable spirit of Rani Lakshmibai. With its powerful performances, stunning visuals, and thought-provoking themes, this movie is sure to leave a lasting impact on audiences.\n",
       "\n",
       "**Rating:** 4/5 stars\n",
       "\n",
       "**Recommendation:** If you're interested in historical biographies, Indian cinema, or simply want to be inspired by a true-life heroine, \"Manikarnika: The Queen of Jhansi\" is an absolute must-watch."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "review_movie(\"https://en.wikipedia.org/wiki/Manikarnika:_The_Queen_of_Jhansi\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d6bc4b7",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
